﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System.Text.Json.Serialization;

namespace Step4.Unit9.Filters
{
    public class CustomerExceptionFilterAttribute : Attribute, IExceptionFilter
    {
        private readonly ILogger<CustomerExceptionFilterAttribute> _logger;

        public CustomerExceptionFilterAttribute(ILogger<CustomerExceptionFilterAttribute> logger)
        {
            _logger= logger;
        }

        // 当发生异常是执行此方法
        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled) // 判断 如果上下文中还有没处理的异常
            {
                var result = new
                {
                    Success = false,
                    Msg = context.Exception.Message,
                    Location = context.RouteData.Values
                };

                context.Result = new JsonResult(result);
                _logger.LogInformation(JsonConvert.SerializeObject(result));
            }
        }
    }
}
